package com.simple.mq.boot.starter;

import com.simple.mq.boot.starter.annotation.SimpleMqInit;
import com.simple.mq.boot.starter.config.SimpleMqCommonConfig;
import com.simple.mq.sdk.register.RegisterConnectInfo;
import com.simple.mq.sdk.register.SimpleMqInitQueuesService;
import com.simple.mq.sdk.register.SimpleRegister;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 项目: simple-mq
 * <p>
 * 功能描述:
 *
 * @author: WuChengXing
 * @create: 2023-09-16 22:53
 **/
public class InitAnnotationBeanPostProcessor implements BeanPostProcessor, Ordered {

    @Resource
    private SimpleMqCommonConfig simpleMqCommonConfig;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 判断是否是被@SimpleRpcService注解的类
        SimpleMqInit simpleMqInit = bean.getClass().getAnnotation(SimpleMqInit.class);
        if (Objects.isNull(simpleMqInit)) {
            // 不存在该注解不操作
            return bean;
        }
        if (!(bean instanceof SimpleMqInitQueuesService)) {
            // 为实现该类不处理
            return bean;
        }
        SimpleMqInitQueuesService simpleMqInitQueuesService = (SimpleMqInitQueuesService) bean;
        SimpleRegister.init(transfer());
        SimpleRegister.registerQueues(simpleMqInitQueuesService.initQueues());
        return bean;
    }

    private RegisterConnectInfo transfer() {
        return RegisterConnectInfo.build(simpleMqCommonConfig.getHost(), simpleMqCommonConfig.getPort());
    }

    @Override
    public int getOrder() {
        return 10;
    }
}
